//
//  Engine.m
//  Simple
//
//  Created by Jeppe Nielsen on 1/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Engine.h"
#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>

#include "TestComponents.hpp"
#include "Matrix4x4.hpp"
#include "Quaternion.hpp"


static TestComponents tester;

@implementation Engine

@synthesize window = _window;

+ (Class) layerClass
{
	return [CAEAGLLayer class];
}

-(id) init {
    self = [super initWithFrame:[[UIScreen mainScreen] bounds]];
    if (self) {
       [[UIApplication sharedApplication] setStatusBarHidden:YES]; 
    }
    return self;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [self makeKeyAndVisible];
    self.backgroundColor = [UIColor blackColor];
    self.userInteractionEnabled = true;
    [self setMultipleTouchEnabled: YES];
    
    
    CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer;
    
    eaglLayer.opaque = YES;
    eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
    
    
    
    
    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
    
    if(!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) {
        //[self release];
        return NO;
    }
    
    tester.Initialize();
    
    [self setupView];
    [self drawView];
    
    gameLoopTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(gameLoop)];
    [gameLoopTimer setFrameInterval:1];
    [gameLoopTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    //gameLoopTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)((1.0 / 60.0)) target:self selector:@selector(gameLoop) userInfo:nil repeats:TRUE];
        
    
    
    return YES;
}

const GLfloat spriteVertices[] = {
    -0.5f, -0.5f,
    0.5f, -0.5f,
    -0.5f,  0.5f,
    0.5f,  0.5f,
};


const GLshort spriteTexcoords[] = {
    0, 0,
    1, 0,
    0, 1,
    1, 1,
};

- (BOOL)createFramebuffer
{
	glGenFramebuffersOES(1, &viewFramebuffer);
	glGenRenderbuffersOES(1, &viewRenderbuffer);
	
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
	[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
	glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
	
    
	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
	
    glGenRenderbuffersOES(1, &depthRenderbuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
        
    
    
	if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
		NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
		return NO;
	}
            
    
    
	
	return YES;
}


- (void)setupView
{
	glViewport(0, 0, backingWidth, backingHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
	glMatrixMode(GL_MODELVIEW);
	
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	
	glVertexPointer(2, GL_FLOAT, 0, spriteVertices);
	glEnableClientState(GL_VERTEX_ARRAY);
	glTexCoordPointer(2, GL_SHORT, 0, spriteTexcoords);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	
   
    
        /*
    spriteImage = 0;
    
	if(spriteImage) {
		
		
		spriteContext = CGBitmapContextCreate(spriteData, width, height, 8, width * 4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
        
		CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), spriteImage);
		
		CGContextRelease(spriteContext);
		
		
		glGenTextures(1, &spriteTexture);
        
		glBindTexture(GL_TEXTURE_2D, spriteTexture);
		
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
		
		free(spriteData);
		
		
		glEnable(GL_TEXTURE_2D);
		
		glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
		
		glEnable(GL_BLEND);
	}
         */
}

static float Rotation = 0;

- (void)drawView
{
    
	[EAGLContext setCurrentContext:context];
	
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
	
    Rotation+=0.02f;
    
    
    Matrix4x4 mat = Matrix4x4::CreateTranslation(Vector3(1,0, sinf(Rotation) * 2));//, 1, Quaternion::Create(0, Vector3(0,0,1)));
    
    glPushMatrix();
    
    glMultMatrixf(mat.GetGlMatrix());
    
    
    
    //glRotatef(3.0f, 0.0f, 1.0f, 1.0f);
        
    
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	
    glPopMatrix();
    
    glEnable(GL_DEPTH_TEST);
    
    tester.Render();
    
    
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
	[context presentRenderbuffer:GL_RENDERBUFFER_OES];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
    tester.Fire();
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
}

-(void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}

-(void) gameLoop {
    tester.Update(1);
    [self drawView];
}

@end
